package com.cook.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cook.dto.recipes.CommentDTO;
import com.cook.entity.Comments;
import com.cook.service.CommentsService;
import com.cook.mapper.CommentsMapper;
import com.cook.vo.recipes.CommentVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* @author black-white spider
* @description 针对表【comments(评论表)】的数据库操作Service实现
* @createDate 2025-10-27 19:54:38
*/
@Service
@Slf4j
public class CommentsServiceImpl extends ServiceImpl<CommentsMapper, Comments>
    implements CommentsService{

    @Autowired
    private CommentsMapper commentsMapper;

    @Override
    public Map<String, Object> getCommentsByCondition(Long recipeId, Long postId, Long userId, Integer pageNum, Integer pageSize) {
        log.info("条件查询评论: recipeId={}, postId={}, userId={}, pageNum={}, pageSize={}", recipeId, postId, userId, pageNum, pageSize);

        try {
            int offset = (pageNum - 1) * pageSize;
            List<CommentVO> comments = commentsMapper.selectCommentsByCondition(recipeId, postId, userId, offset, pageSize);
            int totalCount = commentsMapper.selectCommentsCountByCondition(recipeId, postId, userId);
            int totalPages = (int) Math.ceil((double) totalCount / pageSize);

            Map<String, Object> result = new HashMap<>();
            result.put("list", comments);
            result.put("pageNum", pageNum);
            result.put("pageSize", pageSize);
            result.put("totalCount", totalCount);
            result.put("totalPages", totalPages);
            result.put("recipeId", recipeId);
            result.put("postId", postId);
            result.put("userId", userId);
            result.put("hasNext", pageNum < totalPages);
            result.put("hasPrev", pageNum > 1);

            log.info("条件查询成功，共 {} 条评论", comments.size());
            return result;

        } catch (Exception e) {
            log.error("条件查询评论失败: ", e);
            throw new RuntimeException("查询评论失败");
        }
    }

    @Override
    public Map<String, Object> getCommentsByUserId(Long userId, Integer pageNum, Integer pageSize) {
        log.info("查询用户评论: userId={}, pageNum={}, pageSize={}", userId, pageNum, pageSize);

        try {
            int offset = (pageNum - 1) * pageSize;
            List<CommentVO> comments = commentsMapper.selectCommentsByUserId(userId, offset, pageSize);
            int totalCount = commentsMapper.selectCommentsCountByUserId(userId);
            int totalPages = (int) Math.ceil((double) totalCount / pageSize);

            Map<String, Object> result = new HashMap<>();
            result.put("list", comments);
            result.put("pageNum", pageNum);
            result.put("pageSize", pageSize);
            result.put("totalCount", totalCount);
            result.put("totalPages", totalPages);
            result.put("userId", userId);
            result.put("hasNext", pageNum < totalPages);
            result.put("hasPrev", pageNum > 1);

            log.info("用户评论查询成功，共 {} 条评论", comments.size());
            return result;

        } catch (Exception e) {
            log.error("查询用户评论失败: ", e);
            throw new RuntimeException("查询评论失败");
        }
    }

    @Override
    public Map<String, Object> getAllComments(Integer pageNum, Integer pageSize) {
        log.info("查询所有评论: pageNum={}, pageSize={}", pageNum, pageSize);

        try {
            int offset = (pageNum - 1) * pageSize;
            List<CommentVO> comments = commentsMapper.selectAllComments(offset, pageSize);
            int totalCount = commentsMapper.selectAllCommentsCount();
            int totalPages = (int) Math.ceil((double) totalCount / pageSize);

            Map<String, Object> result = new HashMap<>();
            result.put("list", comments);
            result.put("pageNum", pageNum);
            result.put("pageSize", pageSize);
            result.put("totalCount", totalCount);
            result.put("totalPages", totalPages);
            result.put("hasNext", pageNum < totalPages);
            result.put("hasPrev", pageNum > 1);

            log.info("所有评论查询成功，共 {} 条评论", comments.size());
            return result;

        } catch (Exception e) {
            log.error("查询所有评论失败: ", e);
            throw new RuntimeException("查询评论失败");
        }
    }

    @Override
    @Transactional
    public Long addComment(CommentDTO commentDTO) {
        log.info("添加评论: userId={}, contentLength={}", commentDTO.getUserId(), commentDTO.getContent() != null ? commentDTO.getContent().length() : 0);

        try {
            Comments comment = new Comments();
            BeanUtils.copyProperties(commentDTO, comment);

            int result = commentsMapper.insertComment(comment);
            if (result > 0) {
                log.info("评论添加成功: commentId={}", comment.getCommentId());
                return comment.getCommentId();
            } else {
                throw new RuntimeException("添加评论失败");
            }
        } catch (Exception e) {
            log.error("添加评论失败: ", e);
            throw new RuntimeException("添加评论失败");
        }
    }

    @Override
    @Transactional
    public boolean deleteComment(Long commentId, Long userId, Long recipeId, Long postId) {
        log.info("删除评论: commentId={}, userId={}, recipeId={}, postId={}", commentId, userId, recipeId, postId);

        try {
            int result = commentsMapper.deleteCommentByCondition(commentId, userId, recipeId, postId);
            boolean success = result > 0;

            if (success) {
                log.info("评论删除成功: commentId={}", commentId);
            } else {
                log.warn("评论删除失败: commentId={}", commentId);
            }

            return success;
        } catch (Exception e) {
            log.error("删除评论失败: commentId={}", commentId, e);
            throw new RuntimeException("删除评论失败");
        }
    }

    @Override
    public int getCommentsCountByUserId(Long userId) {
        log.info("统计用户评论数量: userId={}", userId);

        try {
            int count = commentsMapper.selectCommentsCountByUserId(userId);
            log.info("用户 {} 的评论数量: {}", userId, count);
            return count;
        } catch (Exception e) {
            log.error("统计用户评论数量失败: userId={}", userId, e);
            throw new RuntimeException("统计评论数量失败");
        }
    }

    @Override
    public int getCommentsCountByRecipeId(Long recipeId) {
        log.info("统计食谱评论数量: recipeId={}", recipeId);

        try {
            int count = commentsMapper.selectCommentsCountByRecipeId(recipeId);
            log.info("食谱 {} 的评论数量: {}", recipeId, count);
            return count;
        } catch (Exception e) {
            log.error("统计食谱评论数量失败: recipeId={}", recipeId, e);
            throw new RuntimeException("统计评论数量失败");
        }
    }

    @Override
    public int getCommentsCountByPostId(Long postId) {
        log.info("统计动态评论数量: postId={}", postId);

        try {
            int count = commentsMapper.selectCommentsCountByPostId(postId);
            log.info("动态 {} 的评论数量: {}", postId, count);
            return count;
        } catch (Exception e) {
            log.error("统计动态评论数量失败: postId={}", postId, e);
            throw new RuntimeException("统计评论数量失败");
        }
    }

    @Override
    public int getAllCommentsCount() {
        log.info("统计所有评论数量");

        try {
            int count = commentsMapper.selectAllCommentsCount();
            log.info("所有评论数量: {}", count);
            return count;
        } catch (Exception e) {
            log.error("统计所有评论数量失败: ", e);
            throw new RuntimeException("统计评论数量失败");
        }
    }
}




